import { ref, type Ref } from 'vue'
import type { ProjectTreeNode } from '@/store/modules/tree'
import { useTreeStore } from '@/store/modules/tree'
import { ElMessage } from 'element-plus'

export const usePropertyForm = (
  form: Record<string, any>,
  { node, projectId, persist = false, namespace }: { node?: ProjectTreeNode | null; projectId?: number | string | null; persist?: boolean; namespace?: string } = {},
  emit: (e: 'confirm' | 'cancel') => void
): { formRef: Ref<any>; handleConfirm: () => Promise<void> } => {
  // 回填：如果提供 namespace，则将 node.property[namespace] 的字段合并到 form
  if (node?.property) {
    if (namespace && node.property[namespace] && typeof node.property[namespace] === 'object') {
      Object.assign(form, node.property[namespace])
    } else {
      Object.keys(form).forEach(k => {
        if (node.property[k] !== undefined) form[k] = node.property[k]
      })
    }
  }

  const formRef = ref()
  const treeStore = useTreeStore()

  const handleConfirm = async () => {
    if (node) {
      if (!node.property) (node as any).property = {}
      if (namespace) {
        // 深拷贝 form 写入命名空间，避免响应式引用泄漏
        node.property[namespace] = JSON.parse(JSON.stringify(form))
      } else {
        Object.keys(form).forEach(k => { (node!.property as Record<string, any>)[k] = form[k] })
      }
    }
    emit('confirm')

    // 由自动保存机制统一处理；只有在 persist=true 时才立即保存，减少并发冲突
    if (!persist) return
    if (projectId == null) { ElMessage.warning('缺少 projectId，未进行持久化'); return }
    try {
      const resp: any = await treeStore.saveTree(projectId)
      if (resp?.code === 200) ElMessage.success('保存成功')
      else ElMessage.error(resp?.msg || '保存失败')
    } catch (e: any) {
      console.error('保存项目结构失败', e)
      ElMessage.error(e?.message || '保存异常')
    }
  }

  return { formRef, handleConfirm }
}
